<template>
  <a-upload accept="imgae/jpeg,image/png" v-model:file-list="fileList" name="upload" list-type="picture-card"
      class="avatar-uploader" :show-upload-list="true" action="/api/upload" :before-upload="beforeUpload"
      @change="handleChange" :headers="headers" :max-count="1" @preview="handlePreview" @remove="remove">
      <!-- <img v-if="imageUrl" :src="imageUrl" width="100" height="100" alt="avatar" /> -->
      <div>
          <!-- <loading-outlined v-if="loading"></loading-outlined> -->
          <plus-outlined></plus-outlined>
          <div class="ant-upload-text">上传</div>
      </div>
      <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
          <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
  </a-upload>
</template>
<script setup>
import { ref, watch } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons-vue";
import useUserStore from "../store/user"
const emit = defineEmits(["changePic"])
const props = defineProps(["initPic"]) // 外界传入的url
const fileList = ref([]);

// watch无法监听初始化数据
import { handlerPicPath } from '../utils/tools';

const refresh = (newV) =>{
  if (newV) {
    fileList.value({
          uid: -1,
          name: newV,
          status: 'done',
          url: handlerPicPath(newV),
      })
  } else {
    fileList.value = [];
  }
  // const newV = props.initPic;
  
}
// let flag = true;
// watch(
//   () => props.initPic,
//   (newV) => {
//       if (flag) {
//          fileList.value.push({
//           uid: -1,
//           name: newV,
//           status: 'done',
//           url: handlerPicPath(newV),
//         });
//       flag = false;

//       } 
//   })


// 处理单个数据-编辑进入时会有初始数据
const handlerInitData = () => {
  // props.initPic;
}
const userStore = useUserStore();

const headers = {
  Authorization: `Bearer ${userStore.token}`,
}
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

let temp = [];
const loading = ref(false);
const imageUrl = ref('');

const handleChange = info => {

  if (fileList.value.length > 0) {


      const isJpgOrPng = fileList.value[0].type === 'image/jpeg' || fileList.value[0].type === 'image/png';
      if (!isJpgOrPng) {
          fileList.value = temp;
          return
      }
      const isLt2M = fileList.value[0].size / 1024 / 1024 < 2;
      if (!isLt2M) {
          fileList.value = temp;

          return;

      }
  } else {
      emit("changePic", "")

  }


  if (info.file.status === 'uploading') {
      loading.value = true;
      return;
  }
  if (info.file.status === 'done') {

      console.log(info.file.response.path);
      emit("changePic", info.file.response.path)


      // Get this url from response in real world.
      getBase64(info.file.originFileObj, base64Url => {
          // imageUrl.value = base64Url;
          loading.value = false;
      });
  }
  if (info.file.status === 'error') {
      loading.value = false;
      message.error('upload error');
  }
};
const beforeUpload = file => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
      temp = [...fileList.value];
      message.error('You can only upload JPG file!');
      return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
      temp = [...fileList.value];

      message.error('Image must smaller than 2MB!');
      return false;

  }
  return true;
};


// 图片删除
const remove = () => {
  return true
}



// 图片预览

const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
// 预览取消
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
// 转换预览格式
function getPreBase64(file) {
  return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
  });
}
// 预览方法
const handlePreview = async file => {
  if (!file.url && !file.preview) {
      file.preview = await getPreBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

// 暴露数据
defineExpose({refresh});
</script>
<style scoped>
.avatar-uploader>.ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>